<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { ElSelect, ElOption } from "element-plus";
import { getsysDictData, IDiceQueryResult } from "@/api";
const dictData = ref<IDiceQueryResult[]>([]);
interface IProps {
  dictTypeCode?: string,
  typeId?: string,
  options?: IDiceQueryResult[],
  modelValue?: string,
  radiomode?: boolean,
}
interface Emits {
  (t: 'result', v: IDiceQueryResult[]): void,
  (t: 'fetchError', v: string): void,
  (t: 'update:modelValue', v: string): void,
}
const props = defineProps<IProps>();

const events = defineEmits<Emits>();
function initEnv() {
  const { dictTypeCode, typeId, options } = props;
  if (Array.isArray(options)) {
    dictData.value = options;
    return;
  }
  getsysDictData({ dictTypeCode, typeId }).then(
    (data) => {
      events("result", data);
      dictData.value = data;
    },
    (e) => {
      events("fetchError", e);
    }
  );
}

onMounted(() => {
  initEnv();
});
// 监听自定义的字典值的变化
watch(
  () => props.options,
  (_) => {
    dictData.value = _ || []
  }
);
</script>
<template>
  <ElRadioGroup :model-value="modelValue" @update:model-value="$emit('update:modelValue', $event)" v-bind="$attrs"
    v-if="radiomode">
    <ElRadioButton v-for="item of dictData" :key="item.code" :label="item.code">{{
      item.value
    }}</ElRadioButton>
  </ElRadioGroup>
  <ElSelect v-else :model-value="modelValue" @update:model-value="$emit('update:modelValue', $event)" v-bind="$attrs">
    <template #prefix><slot name="prefix"></slot></template>
    <ElOption v-for="item of dictData" :key="item.code" :label="item.value" :value="item.code" />
  </ElSelect>
</template>
